"""
工具调用功能接口
支持LLM使用工具进行交互
"""
from typing import Dict, Any, List, Optional, Callable, Union, Tuple, Set, ClassVar
import json
from .base import Capability, register_capability

@register_capability("tool_calls")
class ToolCallCapability(Capability):
	"""工具调用功能组件接口"""
	
	# 依赖的能力
	dependencies: ClassVar[Set[str]] = set()
	
	def _initialize(self) -> None:
		"""初始化能力"""
		super()._initialize()
		
		# 初始化工具列表和处理函数映射
		self._tools: Dict[str, Dict[str, Any]] = {}
		self._handlers: Dict[str, Callable] = {}
	
	def is_supported(self) -> bool:
		"""
		判断当前提供商和模型是否支持工具调用
		
		Returns:
			是否支持
		"""
		# 默认实现，子类可以重写提供更精确的检测
		return True
	
	def register_tool(self, 
					tool_name: str, 
					description: str, 
					parameters: Dict[str, Any], 
					handler: Callable) -> None:
		"""
		注册一个工具
		
		Args:
			tool_name: 工具名称
			description: 工具描述
			parameters: 参数定义 (JSON Schema)
			handler: 执行工具的处理函数
		"""
		self._tools[tool_name] = {
			"name": tool_name,
			"description": description,
			"parameters": parameters
		}
		self._handlers[tool_name] = handler
	
	def execute_tool_calls(self, 
						 tool_calls: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
		"""
		执行工具调用
		
		Args:
			tool_calls: 工具调用列表
			
		Returns:
			工具执行结果列表
		"""
		results = []
		
		for tool_call in tool_calls:
			tool_name = tool_call.get("function", {}).get("name")
			if not tool_name or tool_name not in self._handlers:
				results.append({
					"tool_call_id": tool_call.get("id"),
					"name": tool_name or "unknown",
					"content": json.dumps({"error": f"工具 '{tool_name}' 未注册"})
				})
				continue
				
			try:
				arguments = tool_call.get("function", {}).get("arguments", "{}")
				if isinstance(arguments, str):
					arguments = json.loads(arguments)
					
				handler = self._handlers[tool_name]
				result = handler(**arguments)
				
				results.append(self.format_tool_response(
					tool_call.get("id"), 
					tool_name,
					result
				))
			except Exception as e:
				results.append({
					"tool_call_id": tool_call.get("id"),
					"name": tool_name,
					"content": json.dumps({"error": str(e)})
				})
				
		return results
	
	def format_tools_for_request(self) -> List[Dict[str, Any]]:
		"""
		将注册的工具格式化为API请求格式
		
		Returns:
			格式化的工具定义列表
		"""
		raise NotImplementedError("必须由具体实现类实现")
		
	def detect_tool_calls(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
		"""
		检测响应中是否包含工具调用
		
		Args:
			response: API响应
			
		Returns:
			工具调用列表，如果没有则为空列表
		"""
		raise NotImplementedError("必须由具体实现类实现")
		
	def format_tool_response(self, 
						   tool_call_id: str, 
						   tool_name: str,
						   result: Any) -> Dict[str, Any]:
		"""
		格式化工具响应消息
		
		Args:
			tool_call_id: 工具调用ID
			tool_name: 工具名称
			result: 工具执行结果
			
		Returns:
			格式化的响应消息
		"""
		content = result
		if not isinstance(result, str):
			content = json.dumps(result)
			
		return {
			"role": "tool",
			"tool_call_id": tool_call_id,
			"name": tool_name,
			"content": content
		}
